#
# "@(#) $Id: LArtistView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from kdeemul import *
from Library import *
from utils import *
from LTrackDrag import *
from LSettings import *

class LArtistViewItem(KListViewItem):
	def __init__(self,container,artist):
		KListViewItem.__init__(self,container,artist)
		self.sortKey = QString("ZA%s" % self.normalize(artist))
		self.setDragEnabled(True)

	def normalize(self,artist):
		for article in ["The ", "El ", "La ", "Los ", "Las ", "Le ", "Les "]:
			alen = len(article)
			if artist[0:alen]==article: artist = artist[alen:]
		return artist.upper()

	def key(self,column,ascending):
		return self.sortKey

	def artist(self):
		return unikode(self.text(0))


class LAllArtistsViewItem(LArtistViewItem):
	def __init__(self,container,count):
		LArtistViewItem.__init__(self,container,unikode(i18n("All (%d Artists)")) % (count))
		self.akey = QString('AA')
		self.dkey = QString('ZZ')
		self.setDragEnabled(False)
	
	def setCount(self,count):
		self.setText(0,unikode(i18n("All (%d Artists)")) % (count))

	def key(self,column,ascending):
		if ascending:
			return self.akey
		else:
			return self.dkey

	def artist(self):
		return None

class LArtistView(KListView):
	def __init__(self, container):
		KListView.__init__(self,container,"artists")
		self.bulkEdit = False
		self.settings = LSettings.settings()
		self.setSelectionMode(QListView.Extended)
		self.library = Library.mainLibrary()
		self.playlist = self.library.playlistWithName("Library")
		if self.playlist==None:
			print "Error: LArtistView has no playlist"
		self.allItem = None
		self.setShowSortIndicator(True)
		self.setAlternateBackground(QColor())
		self.loadHeaders()
		self.loadArtists()
		self.connect(self,SIGNAL("selectionChanged()"),self.selectArtistItems)
		self.playlist.connect(PYSIGNAL("addedTrack"),self.addedTrack)
		self.playlist.connect(PYSIGNAL("removedTrack"),self.refresh)
		self.library.connect(PYSIGNAL("changedTrackArtistOrAlbum"),self.refresh)
		self.library.connect(PYSIGNAL("bulkEditBegin"),self.bulkEditBegin)
		self.library.connect(PYSIGNAL("bulkEditEnd"),self.bulkEditEnd)

	def bulkEditBegin(self):
		self.bulkEdit = True
	
	def bulkEditEnd(self):
		self.bulkEdit = False
		self.refresh()

	def selectArtistItems(self):
		if self.allItem.isSelected():
			item = self.firstChild()
			while item:
				if item!=self.allItem and item.isSelected():
					item.setSelected(False)
				item = item.itemBelow()
			self.selectArtists(None)
		else:
			artists = self.selectedArtists()
			self.selectArtists(artists)

	def selectedArtists(self):
		artists = []
		item = self.firstChild()
		while item:
			if item.isSelected():
				artists.append(item.artist())
			item = item.itemBelow()
		return artists
	
	def selectArtists(self,artists):
		if artists==None:
			self.settings['Main Library Artists'] = []
		else:
			self.settings['Main Library Artists'] = artists
		self.emit(PYSIGNAL("selectArtists"),(artists,None))

	def loadFromPrefs(self):
		#print "loading artists from prefs"
		artists = self.settings.get('Main Library Artists',[])
		for artist in artists:
			self.selectItemForArtist(artist)
		self.selectArtists(artists)
	
	def selectItemForArtist(self,artist):
		item = self.firstChild()
		while item:
			if item.artist()==artist:
				item.setSelected(True)
				break
			item = item.itemBelow()

	def loadHeaders(self):
		self.addColumn(i18n("Artist"))
		self.setFullWidth(True)
		self.setSorting(0,self.settings.get('Main Library Artists Sort Ascending',True))

	def loadArtists(self):
		#print "LArtistView reloading",self.bulkEdit
		if not self.bulkEdit:
			self.clear()
			if self.playlist:
				artists = {}
				tracks = self.playlist.tracks
				for track in tracks:
					if track:
						artist = track.artist
						if artist!=None and len(artist)>0:
							artists[artist.upper()] = artist
				artists = artists.values()
				#artists.sort()
				sortingDirection = self.settings.get('Main Library Artists Sort Ascending',True)
				self.setSorting(-1,True)
				self.setUpdatesEnabled(False)
				self.blockSignals(True)
				self.allItem = LAllArtistsViewItem(self,len(artists))
				for artist in artists:
					item = LArtistViewItem(self,artist)
				self.setSorting(0,sortingDirection)
				self.blockSignals(False)
				self.setUpdatesEnabled(True)
				self.update()
			else:
				print "Artist playlist in None"

	def refresh(self):
		if not self.bulkEdit:
			self.loadArtists()

	#
	# we attempt to optimize the common case of
	# adding a track to keep refreshes to a minimum
	#
	def addedTrack(self,playlist,trackID):
		if not self.bulkEdit:
			track = self.playlist.trackWithTrackID(trackID)
			if track:
				artist = unikode(track.artist)
				if artist and len(artist)>0:
					item = self.firstChild()
					count = 0
					while item:
						count = count+1
						if unikode(item.artist())==artist:
							return
						item = item.itemBelow()
					item = LArtistViewItem(self,artist)
					self.allItem.setCount(count)

	def dragObject(self):
		artists = self.selectedArtists()
		#print "dragging",artists
		trackIDs = self.playlist.trackIDsForArtists(artists)
		#print "dragging",trackIDs
		drag = LTrackDrag(trackIDs,self.playlist,self)
		drag.dragCopy()

	def setSorting(self,column,ascending):
		KListView.setSorting(self,column,ascending)
		self.settings['Main Library Artists Sort Ascending'] = not not ascending
